package com.ultrasoft.farmasoft.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.ultrasoft.farmasoft.domain.Access;
import com.ultrasoft.farmasoft.domain.Menu;
import com.ultrasoft.farmasoft.domain.Option;
import com.ultrasoft.farmasoft.domain.Submenu;
import com.ultrasoft.farmasoft.domain.User;
import com.ultrasoft.farmasoft.domain.Userpharmacy;
import com.ultrasoft.farmasoft.service.PortadaDepartmentsService;
import com.ultrasoft.farmasoft.service.HumanResourcesService;
import com.ultrasoft.farmasoft.util.UtilCommon;
import com.ultrasoft.farmasoft.util.UtilConverter;
import com.ultrasoft.farmasoft.util.UtilUseFulTree;
import com.ultrasoft.farmasoft.domain.Article;
import com.ultrasoft.farmasoft.domain.Section;

@Controller
@SessionAttributes({"s_UserPharmacy"}) 
public class UserController {
	// this four attributes always should be in all controllers and sessionControl(HttpServletRequest request) method
	private HttpSession session;
	private Userpharmacy s_UserPharmacy;
	private int s_userId;
	private int s_pharmacyId;
	private final PortadaDepartmentsService portadaDepartmentsService;	
	private final HumanResourcesService humanResourceService;	
	
	@Autowired
    public UserController(HumanResourcesService humanResourceService,PortadaDepartmentsService portadaDepartmentsService) {
        this.humanResourceService = humanResourceService;
        this.portadaDepartmentsService= portadaDepartmentsService; // con esto recupero los servicios del departamento
    }	
	
	private boolean sessionControl(HttpServletRequest request){
		boolean res = false;
		session = request.getSession(true);
		if(session.getAttribute("s_UserPharmacy") != null){
			s_UserPharmacy 	= (Userpharmacy)session.getAttribute("s_UserPharmacy");
			s_userId 		= s_UserPharmacy.getUser().getUserId();
			s_pharmacyId 	= s_UserPharmacy.getPharmacy().getPharmacyId();
			res = true;
		}
		return res;
	}
	
	private List<Menu> loadMenuListBySubmenuByOptionByAccess(Integer userId,Integer pharmacyId){
		List<Menu> tempMenu = new ArrayList<Menu>();		
		List<Access> accessList = humanResourceService.getAccessList(userId, pharmacyId);		
		List<Menu> menuList = humanResourceService.getMenuList();
		for (Menu menu : menuList) {
			for (Access access : accessList) {
				if(access.getAccessPK().getMenuId() == menu.getMenuId()){
					List<Submenu> submenuList = humanResourceService.getSubMenuList(menu.getMenuId()); 
					for (Submenu submenu : submenuList) {
						List<Option> optionList = humanResourceService.getOptionList(submenu.getSubmenuPK().getMenuId(),submenu.getSubmenuPK().getSubmenuId());
						for (Option option : optionList) {
							List<Access> ta= new ArrayList<Access>();
							for (Access a : accessList) {
								if(option.getOptionPK().getMenuId() == a.getAccessPK().getMenuId()
										&& option.getOptionPK().getSubmenuId() == a.getAccessPK().getSubmenuId()
										&& option.getOptionPK().getOptionId() == a.getAccessPK().getOptionId())
									ta.add(a);
							}
							option.setAccessCollection(ta);
						}
						submenu.setOptionCollection(optionList);
					}
					menu.setSubmenuCollection(submenuList);
					tempMenu.add(menu);
					break;
				}					
			}
		}
		return tempMenu;
	}
		
	@RequestMapping(value="/closeSesion", method=RequestMethod.GET)
	protected String removeSession(SessionStatus status,HttpServletRequest request,Model model) {
		session = request.getSession(true);
		if((Userpharmacy)session.getAttribute("s_UserPharmacy")!=null){
			status.setComplete();			//complet session
			session.setAttribute("s_UserPharmacy",null);
		}
		if(UtilConverter.converterStringToInteger(request,"e") == 1 || UtilConverter.converterStringToInteger(request,"e") == 2)
			model.addAttribute("check",UtilConverter.converterStringToInteger(request,"e"));
		return "redirect:/index";
	}	
	
	@RequestMapping(value="/index",method = RequestMethod.GET)
    protected String handleIndex(HttpServletRequest request,Model model) throws ServletException {
		session = request.getSession();
    	if((Userpharmacy)session.getAttribute("s_UserPharmacy") == null){
       		
    		List<Article> departamentos= portadaDepartmentsService.getArticleDistintRegionId();
    		model.addAttribute("Departaments", departamentos);
    		    		
			UtilUseFulTree util=new UtilUseFulTree();

    		User user = new User();
        	model.addAttribute("user",user);
        	return UtilCommon.fFront+"index";																				
    	}else{
    		return "redirect:/mainFront?";	
    	}			
    }
	
	@RequestMapping(value="/index2",method = RequestMethod.GET)
    protected String handleIndex2(HttpServletRequest request,Model model) throws ServletException {
		int p = UtilConverter.converterStringToInteger(request,UtilCommon.pharmacyId_);
		int u = UtilConverter.converterStringToInteger(request,UtilCommon.userId_);
		if(p != -1 && u != -1){
			session= request.getSession(true);   
			Userpharmacy temp = humanResourceService.searchUserPharmacyByPharmacyIdByUserId(p,u);
	        session.setAttribute("s_UserPharmacy",temp);
	        session.setAttribute("s_menuHeadList",loadMenuListBySubmenuByOptionByAccess(temp.getUser().getUserId(),temp.getPharmacy().getPharmacyId()));
			return "redirect:/mainFront?";
		}else
			return "redirect:/index";
    }
	
	/*****MEJORANDO QUIENES SOMOS****/
	@RequestMapping(value="/quienesSomos",method = RequestMethod.GET)
    protected String quienesSomos(HttpServletRequest request,Model model) throws ServletException {
        	return UtilCommon.fFront+"quienesSomos";																						
    }
	
	@RequestMapping(value="/contactenos",method = RequestMethod.GET)
    protected String contactenos(HttpServletRequest request,Model model) throws ServletException {
        	return UtilCommon.fFront+"contactenos";																				
    }

	@RequestMapping(value="/index",method = RequestMethod.POST)
	protected String onSubmitIndex(Model model,User user,HttpServletRequest request,@RequestParam String action){    	
    	if(!action.equals("Registrarse")){
    		List<Userpharmacy> listUserPharmacy = humanResourceService.getListUserPharmacy(user.getLogin(),user.getPassword());
    		if(!listUserPharmacy.isEmpty()){
    			if(listUserPharmacy.size() == 1){
    				session= request.getSession(true);        
    		        session.setAttribute("s_UserPharmacy",listUserPharmacy.get(0));
    		        session.setAttribute("s_menuHeadList",loadMenuListBySubmenuByOptionByAccess(listUserPharmacy.get(0).getUser().getUserId(),listUserPharmacy.get(0).getPharmacy().getPharmacyId()));
    				return "redirect:/mainFront?";
    			}else{
    				List<Integer> list = new ArrayList<Integer>();
    			
    				for (Userpharmacy userpharmacy : listUserPharmacy) {
						list.add(userpharmacy.getPharmacy().getPharmacyId());
					}
    				model.addAttribute("userIdTemp",listUserPharmacy.get(0).getUser().getUserId());
    				return "redirect:/index";// dialog
    			}
    		}else{
    			if(user.getLogin().length() == 0 || user.getPassword().length() == 0)
    				model.addAttribute("e",2);
    			else
    				model.addAttribute("e",1);
    			return "redirect:/mainFront?";
	        }														
        }else 
        	return "redirect:/closeSesion";
    }  	
	@RequestMapping(value="/mainFront", method = RequestMethod.GET)	
	protected String handleFront(Model model, HttpServletRequest request) throws ServletException {
       	if(this.sessionControl(request)){    	
       		return UtilCommon.fPharmacy+"main";																				
		}else{
			if(UtilConverter.converterStringToInteger(request,"e") == 1 || UtilConverter.converterStringToInteger(request,"e") == 2)
				model.addAttribute("e",UtilConverter.converterStringToInteger(request,"e"));
			return "redirect:/closeSesion"; 
		}
	}
	
	@RequestMapping(value = "/ajaxSelectedPharmacy", method = RequestMethod.GET)
   	protected @ResponseBody String handleRequestAjaxAcademicAdminBooksShowTableByStudyPlan(@RequestParam Integer userId,HttpServletRequest request)throws JsonIOException{		
		List<Userpharmacy> userPharmacyList = humanResourceService.getUserPharmacyList(userId);
		JsonArray groupArray = new JsonArray();
        if(!userPharmacyList.isEmpty()){
			for (Userpharmacy u : userPharmacyList) {
	            JsonObject groupJSON = new JsonObject();
	            groupJSON.addProperty("pharmacyId",u.getUserpharmacyPK().getPharmacyId());
	            groupJSON.addProperty("userId",u.getUserpharmacyPK().getUserId());
	            groupJSON.addProperty("name",u.getPharmacy().getName());
	            groupArray.add(groupJSON);
	        }
		}else{
			JsonObject groupJSON = new JsonObject();
            groupJSON.addProperty("name","");
            groupArray.add(groupJSON);
		}
    	return groupArray.toString();
    }	
	
	/* DEPARTAMENTS*/
	@RequestMapping(value="/homeDepartamemts",method = RequestMethod.GET)
    protected String homeDepartamts(HttpServletRequest request,Model model, int _dept) throws ServletException {
		
		Integer dato= _dept;   			
		//Return List Articles with equal IdRegion Active
		List<Article> articleArtive= portadaDepartmentsService.getArticleListWithIdRegionActive(dato, true);
		model.addAttribute("articulosActivos",articleArtive);
		
		List<Section> ListSectionWithRegionId= portadaDepartmentsService.getSectionWithRegionId(dato, true);
		model.addAttribute("listSection",ListSectionWithRegionId);

		/*Array Random*/
		int rand = (int) (Math.random() * (ListSectionWithRegionId.size()));
		//System.out.println("<---->"+rand);
		
		List<Article> departamento= portadaDepartmentsService.getArticleDistinctRegionRegains(dato);
		model.addAttribute("Departament", departamento);
		
		List<Article> departamentos= portadaDepartmentsService.getArticleDistintRegionId();
		model.addAttribute("comboDepartaments", departamentos);
		
        return UtilCommon.pHomeDepartments+"homeDepartamts";																				
    }
	
	/* articles, section and Departments*/
	@RequestMapping(value="/articlesSectiDepartament",method = RequestMethod.GET)
    protected String articlesDepartments(HttpServletRequest request,Model model, int _dept, int _arti, int _sect) throws ServletException {

		Integer dato= _dept;	
		List<Article> departamentos= portadaDepartmentsService.getArticleDistintRegionId();
		model.addAttribute("comboDepartaments", departamentos);
				
		//Return List Articles with equal IdRegion Active
		List<Article> articleArtive= portadaDepartmentsService.getArticleListWithIdRegionActive(dato, true);
		model.addAttribute("articulosActivos",articleArtive);
		
		//Return List Section with Article equal
		List<Section> sectionActive= portadaDepartmentsService.getSectionListWithIdArticleActive(_arti, true);
		model.addAttribute("sectionesActivas", sectionActive);
		
		//list section with dept.
		List<Section> listSection= portadaDepartmentsService.getSectionWithRegionId(dato, true);
		model.addAttribute("listaOfSection",listSection);
		
		List<Section> oneListSectio= portadaDepartmentsService.getSectionList(_sect);
		model.addAttribute("unaSeccion",oneListSectio);
		
		return UtilCommon.pHomeDepartments+"articlesSectiDepartament";
	}
	
	/*All articles of section*/
	@RequestMapping(value="/articlesDepartmentsAll",method = RequestMethod.GET)
    protected String articlesDepartmentsAll(HttpServletRequest request,Model model, int _dept) throws ServletException {
		Integer dato= _dept;
		List<Article> articleArtive= portadaDepartmentsService.getArticleListWithIdRegionActive(dato, true);
		model.addAttribute("articulosActivos",articleArtive);

		List<Section> listSection= portadaDepartmentsService.getSectionWithRegionId(_dept, true);
		model.addAttribute("listaOfSection",listSection);

		List<Article> departamentos= portadaDepartmentsService.getArticleDistintRegionId();
		model.addAttribute("comboDepartaments", departamentos);
				
		return UtilCommon.pHomeDepartments+"articlesDepartmentsAll";/*llama a articlesDepartamentsAlljsp*/
	}
	
	
}
